package com.xiaohong.search.test;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 批量请求更新的Demo
 */
public class ElasticSearchBulkOpreation {

	public static void main(String[] args) throws IOException {
		//当es用用户名和密码连接时
		//初始化ES操作客户端
		final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials("elastic", "123456"));  //es账号密码（默认用户名为elastic）
		RestHighLevelClient client =new RestHighLevelClient(
				RestClient.builder(new HttpHost("192.168.6.1",9200,"http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
					public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
						httpClientBuilder.disableAuthCaching();
						return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
					}
				})
		);

		//TODO 当es无密码时可以直接使用下面这个创建客户端
		//RestHighLevelClient client =  new RestHighLevelClient(RestClient.builder(new HttpHost(
		//		"192.168.6.1",9200,"http"
		//)));


		//创建批量请求
		BulkRequest bulkRequest = new BulkRequest();
		//bulkRequest.add(new IndexRequest("sse_test").id("7").source(XContentType.JSON,"qq","哆啦A梦","weixin","123456"));
		Map<String,Object> map = new HashMap<>();
		map.put("qq","123456789");
		map.put("weixin","123456789");
		map.put("phone","123456789");
		Map<String,Object> map1 = new HashMap<>();
		map1.put("qq","1234");
		map1.put("weixin","123456789");
		map1.put("phone","1234");
		bulkRequest.add(new IndexRequest("sse_test").id("9").source(map));
		bulkRequest.add(new UpdateRequest("sse_test","9").doc(map1).upsert());
		client.bulk(bulkRequest, RequestOptions.DEFAULT);
		System.out.println("结束");

	}
}
